package erfgame.frontend.desktop.view.terrain.iso.interaction.position;

import java.awt.Point;

import erfgame.core.Point3D;
import erfgame.core.Rectangle3D;
import erfgame.core.world.World;
import erfgame.core.world.terrain.TerrainUpdate;
import erfgame.core.world.terrain.TerrainUpdateGroup;
import erfgame.core.world.terrain.TerrainUtils;

import erfgame.frontend.desktop.view.terrain.iso.interaction.TerrainUpdatePositionFactory;

public class TileCenterLayerTopTerrainUpdatePositionFactory implements
		TerrainUpdatePositionFactory {

	protected int blockGranularity;
	protected int zOffset;
	
	public TileCenterLayerTopTerrainUpdatePositionFactory() {
		this(1);
	}
	
	public TileCenterLayerTopTerrainUpdatePositionFactory(int blockGranularity) {
		this.blockGranularity = blockGranularity;
	}
	
	public void setZOffset( int zOffset ) {
		this.zOffset = zOffset;
	}
	
	public Point3D getPosition(
			Point3D terrain, 
			TerrainUpdateGroup terrainUpdate,
			World world
	) {
		if( terrain != null ) 
		{
			Point grid = world.getGridCoordinates(
					terrain.x, 
					terrain.y
			);
			Rectangle3D bounds = terrainUpdate.getBounds();
			int x = TerrainUtils.getTx(grid.x, grid.y, world) - bounds.minX - bounds.getWidth()/2;
			int y = TerrainUtils.getTy(grid.x, grid.y, world) - bounds.minY - bounds.getHeight()/2;
			int z = getZ( terrain, terrainUpdate, world ) + zOffset;
			return new Point3D(x, y, z);
		}
		else
		{
			return null;
		}
	}
	
	public int getZ( Point3D terrain, TerrainUpdateGroup terrainUpdate, World world ) {
		int depthMult = world.getBlockDepth() * blockGranularity; 
		int z = Math.max( 0, (terrain.z-1) / depthMult ) * depthMult;
		return z;
	}

}
